﻿
/****** Object:  Trigger dbo.TRG_ReplicateCodePaymentProcessor    Script Date: 10/14/2009 10:39:58 PM ******/
CREATE TRIGGER TRG_ReplicateCodePaymentProcessor ON dbo.CodePaymentProcessor 
FOR Insert, Update, Delete
AS
set nocount on

declare @company varchar(50)
declare cursorReplicateCodePaymentProcessor cursor for select name from tblCompany
open cursorReplicateCodePaymentProcessor
fetch next from cursorReplicateCodePaymentProcessor into @company
while @@fetch_status = 0
begin
	declare @sql varchar(2000)
	set @sql =
		'insert into ' + @company + '..CodePaymentProcessor select T1.* from CodePaymentProcessor T1' +
		' left outer join ' + @company + '..CodePaymentProcessor T2 on T1.ProcessorCode = T2.ProcessorCode' +
		' where T2.ProcessorCode is null'
	exec( @sql )
	set @sql =
		'update T1 set Name = T2.Name, [Active] = T2.[Active], DefaultOnlineSystemID = T2.DefaultOnlineSystemID ' +
		' from ' + @company + '..CodePaymentProcessor T1' +
		' join CodePaymentProcessor T2 on T1.ProcessorCode = T2.ProcessorCode'
	exec( @sql )
	set @sql =
		'delete from T1 ' +
		' from ' + @company + '..CodePaymentProcessor T1' +
		'	left outer join CodePaymentProcessor T3 on T1.ProcessorCode = T3.ProcessorCode' +
		' where T3.ProcessorCode is null'
	exec( @sql )
	fetch next from cursorReplicateCodePaymentProcessor into @company
end
close cursorReplicateCodePaymentProcessor
deallocate cursorReplicateCodePaymentProcessor        
